<template>
  <a-modal
    v-model:visible="config.visible"
    :title="title"
    title-align="start"
    width="600px"
    @before-ok="handleBeforeOk"
    unmountOnClose
  >
    <a-form :model="form" ref="formRef">
      <a-form-item
        field="fontName"
        label="名称"
        :rules="[{ required: true, message: '请输入名称' }]"
        :validate-trigger="['input']"
      >
        <a-input v-model="form.fontName" placeholder="请输入名称" allow-clear />
      </a-form-item>
      <a-form-item label="字体文件" required>
        <a-upload accept=".ttf" @before-upload="onBeforeUpload" v-model:file-list="fileList" :action="`${BASE_UPLOAD_URL}/canvasapi/app/canvas/fontUpload`" :headers="headers" :limit="1" tip="支持格式：.ttf ，单个文件不能超过20MB">
        </a-upload>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { addFont } from '@/api/graph.js'
import { BASE_UPLOAD_URL } from '@/config/index.js'
import { getToken, serializeRequestForm } from '@/utils/index.js'
import { Message } from '@arco-design/web-vue'
import { reactive, computed, ref } from 'vue'

const formRef = ref()
const form = reactive({
  fontName: null,
  tiffFile: null
})
const headers = computed(() => {
  return {
    token: getToken()
  }
})
const fileList = ref([])
const config = reactive({
  visible: false,
  modalType: 'add'
})
const title = computed(() => {
  return config.modalType === 'add' ? '新增' : '编辑'
})
const onBeforeUpload = (file) => {
  if (file) {
    const { size } = file
    const isLt20M = size / 1024 / 1024 <= 20
    if (isLt20M) {
      return true
    } else {
      Message.warning('上传文件过大，请重新选择')
      return false
    }
  }
}
const handleBeforeOk = async () => {
  const errors = await formRef.value.validate()
  if (errors) {
    return false
  }
  const tiffFile = fileList.value.find(item => item.status === 'done')
  if (!tiffFile) {
    Message.warning('请上传字体文件')
    return false
  }
  console.log(tiffFile)
  form.tiffFile = tiffFile.response.data
  const params = serializeRequestForm(form)
  await addFont(params)
  Message.success('保存成功')
  emits('on-success')
}
const resetForm = () => {
  form.tiffFile = null
  form.fontName = null
  fileList.value = []
}
const emits = defineEmits(['on-success'])
const init = async (type = 'add') => {
  resetForm()
  config.modalType = type
  config.visible = true
}
defineExpose({
  init
})
</script>

<style lang="scss" scoped></style>
